package org.jeecg.modules.netty.protocol.v4;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class DataFrameUtil {
    public static final int magic = 0xAA55;//43605
    public static final byte version=4;
    public static final byte enctype=0;
    public static final byte reserved=0;
    public static final Charset CHARSET = StandardCharsets.UTF_8;
    private static byte type=1;




    public static int crc16(char[] chars)
    {
        int crc = 0xFFFF;
        int size = chars.length;
        if(chars!=null&&size>0){
            for(int i=0;i<size;i++){
                crc = (crc >> 8) | (crc<<24)>>>16;
                crc ^= chars[i];
                crc ^= (crc<<24)>>>28;
                crc ^= crc << 12;
                crc = (crc <<16)>>>16;
                crc ^= (crc & 0xFF) << 5;
            }
        }
        return crc;
    }

    public static DataFrame createPackage(String playload) {
        int crc16 = crc16(playload.toCharArray());
        DataFrame dataFram = new DataFrame();
        dataFram.setMagic(DataFrameUtil.magic);
        dataFram.setCrc(crc16);
        dataFram.setEnctype(DataFrameUtil.enctype);
        dataFram.setReserved(DataFrameUtil.reserved);
        dataFram.setVerion(DataFrameUtil.version);
        dataFram.setPlayloadlen(playload.length());
        dataFram.setType(DataFrameUtil.type);
        dataFram.setPlayload(playload);
        return dataFram;
    }



}
